package com.gitee.jktantan.datasource.monitor.config;

import com.codahale.metrics.MetricRegistry;
import com.gitee.jktantan.datasource.monitor.toolkit.HikariCPUtils;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;


/**
 * 配置是否启用监测
 */
@Slf4j
public class DataSourceMonitorRegister implements InitializingBean {
    private boolean enable = true;

    @Autowired
    private MetricRegistry metricRegistry;

    @Autowired
    private List<DataSource> dataSources;

    @Resource
    private HikariCPUtils hikariCPUtils;

    public boolean isEnable() {
        return enable;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }


    /**
     * 配置数据源
     * 在这里配置的数据源是没有HealthCheck的功能的
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        if (enable) {
            List<HikariDataSource> hikariDataSources = hikariCPUtils.getHikariDataSourceList(dataSources);
            log.debug("开始给HikariCP数据源配置计量");
            for (HikariDataSource hikariDataSource : hikariDataSources) {
                if (hikariDataSource.getMetricRegistry() == null) {
                    hikariDataSource.setMetricRegistry(metricRegistry);
                }
            }
        }
    }
}
